<template>
  <div class="hos-offices">
    <el-select class="offices-input" v-model="dept1" placeholder="选择一级科室" :style="seletStyle">
      <el-option v-for="item in departmentList" :key="item.id ? item.id : Math.random()*1000" :label="item.dValue" :value="item.dKey" />
    </el-select>
    <el-select class="offices-input" v-model="dept2" placeholder="选择二级科室" :style="seletStyle">
      <el-option v-for="item in subDepart" :key="item.id ? item.id : Math.random()*1000" :label="item.dValue" :value="item.dKey" />
    </el-select>
  </div>
</template>

<script>
// 二级联动
import { departmentList, subDepartmentList } from "data/listBody"
import queryList from "utils/queryList";
let changePower = true;

export default {
  name: "hosOffices",
  props:['seletStyle','defaultValue'],
  data() {
    return {
      departmentList,   
      subDepart: [], //二级科室
      dept1: "",
      dept2: "",
    };
  },
  mounted(){
    this.dataInit();
  },
  methods: {
    dataInit(){
      let datas = JSON.parse(JSON.stringify(departmentList));
      this.departmentList = this.addAll(datas);
    },
    addAll(arry){ //地址添加全部
      let param = {
          id:'',
          dKey:'',
          dValue:'全部',
        }
        let filterArr = arry.filter(item => {
          return item.dValue !== '全部';
        })
        arry.unshift(param);
        return arry;
    },
    handleData(num) {
      //处理二级科室
      if( !num ) return;
      let datas = this.lodash.filter(subDepartmentList, (item) => {
        return item.parentKey === num
      })
      this.subDepart = this.addAll(datas);
    },
    getData(){
      let params = {
        dept1: this.dept1,
        dept2: this.dept2
      }
      return params;
    }
  },
  watch: {
    defaultValue(){
      if( this.defaultValue ) {
        const { dept1, dept2 } = this.defaultValue;
        changePower = false;

        // 一级科室
        if( !dept1 ) return changePower = true;
        this.handleData(dept1);
        this.dept1 = dept1;

        // 二级科室
        setTimeout(() => {
          if( !dept2 ) return changePower = true;
          this.dept2 = dept2;
          changePower = true;
        }, 500);
      }
    },
    dept1: function(curVal, oldVal) {
      if( !curVal || !changePower ) return;
      this.subDepart = [];
      this.dept2 = "";
      this.handleData(curVal);
      this.$emit("deptChange", this.getData());
    }
  }
};
</script>
<style lang="less" scoped>
@import url("./../assets/less/color.less");
.hos-offices {
  display: flex;
  .offices-input{
    margin-right: 20px;
    width: 210px;
    &.last-child{
      margin-right: 0;
    }
  }
}
</style>